<?php

class TmpInbound_IndexController extends Zend_Controller_Action
{
	protected $_object;
	public $string_inbound_type = 'xuất';
	public $string_inbound_type_2 = 'nhận';
	public $inbound_type = 1;
	public $inbound_warehouse_group_code;
	public $string_warehouse_group_name;

	//init
	public function init()
	{
		//tạo đối tượng chính của module
		$this->_object = new Admin_Model_TmpInbound ();
	}

	//ham ho tro _setInboundString
	protected function _setInboundString($inbound_warehouse_group_code)
	{
		//lấy tên nhóm kho
		switch ($inbound_warehouse_group_code)
		{
			case 'NVL' :
				$this->string_warehouse_group_name = 'nguyên vật liệu';
				break;
			case 'BB' :
				$this->string_warehouse_group_name = 'bao bì';
				break;
			case 'TP' :
				$this->string_warehouse_group_name = 'thành phẩm';
				break;
		}
		
		//thay thế ngôn ngữ ứng với loại phiếu nhập, phiếu xuất riêng
		$array_replace_caption = array ('string_inbound_type' => $this->string_inbound_type, 'string_inbound_type_2' => $this->string_inbound_type_2 );
		
		//gan tham so
		$this->inbound_warehouse_group_code = $inbound_warehouse_group_code;
		
		//lấy tiêu đề 
		$this->_helper->common->setCaptions ( $array_replace_caption, array ("inbound", "inbound-detail", "inventory" ) );
		
		//truyền dữ liệu ra view
		$this->view->string_warehouse_group_name = $this->string_warehouse_group_name;
		$this->view->string_inbound_type_2 = $this->string_inbound_type_2;
		$this->view->string_inbound_type = $this->string_inbound_type;
		$this->view->inbound_type = $this->inbound_type;
		$this->view->inbound_warehouse_group_code = $this->inbound_warehouse_group_code;
	}

	//tính năng copy 1 phiếu ra phiếu mới
	protected function copyAction()
	{
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		
		//forward
		$this->_forward ( 'copy', 'index', 'inbound', array ('id' => $id, 'tmp' => '1' ) );
	}

	//xem danh sách tất cả 
	public function indexAction()
	{
		//lấy tham số
		$request = $this->_request;
		$adminAction = $request->getParam ( 'adminAction', '' );
		$layout = $request->getParam ( 'layout', '' );
		$inbound_code = $request->getParam ( 'inbound_code', '' );
		$report_type = 0; //$request->getParam ( 'report_type', 0 );
		$inbound_name = $request->getParam ( 'inbound_name', '' );
		$inbound_company_code = $request->getParam ( 'inbound_company_code', '' );
		$inbound_create_user = $request->getParam ( 'inbound_create_user', '' );
		$inbound_warehouse_code = $request->getParam ( 'inbound_warehouse_code', '' );
		$inbound_reason_code = $request->getParam ( 'inbound_reason_code', '' );
		$inbound_create_time_a = $request->getParam ( 'inbound_create_time_a', '' );
		$inbound_create_time_b = $request->getParam ( 'inbound_create_time_b', '' );
		$inbound_detail_product_code = $request->getParam ( 'inbound_detail_product_code', '' );
		$inbound_detail_sub_product_code = $request->getParam ( 'inbound_detail_sub_product_code', '' );
		$product_group_code = $request->getParam ( 'product_group_code', '' );
		$account_username = $request->getParam ( 'account_username' );
		$inbound_warehouse_group_code = $request->getParam ( 'inbound_warehouse_group_code' );
		
		//layout
		if ($layout != '')
			$this->getHelper ( 'Layout' )->setLayout ( $layout );
		
		//set tham số
		$this->_setInboundString ( $inbound_warehouse_group_code );
		
		//tạo form
		$form = new TmpInbound_Form_TmpInbound_Search ( $this );
		
		//select kho nhập hàng
		$warehouse = new Admin_Model_Warehouse ();
		$warehouses = $warehouse->fetchAllBase ( NULL, 'warehouse_name ASC' );
		$warehouses = $warehouse->toArray2 ( $warehouses, 'warehouse_code', 'warehouse_name' );
		$form->inbound_warehouse_code->setMultiOptions ( array ('' => '- Chọn -' ) + $warehouses );
		
		//Lay thong tin nguoi tao phieu
		if ($account_username == "")
		{
			$account = new Admin_Model_Account ();
			$sql = "
			SELECT * 
			FROM view_account
			ORDER BY account_fullname ASC";
			$accounts = $account->queryBase ( $sql );
			$accounts = $account->toArray2 ( $accounts, 'account_username', 'account_fullname' );
			$form->inbound_create_user->setMultiOptions ( array ('' => '- Chọn -' ) + $accounts );
		}
		
		//lấy khách hàng hoac nha cung cap
		if ($this->inbound_type == 0) //nhap lấy ncc
		{
			$supplier = new Admin_Model_Supplier ();
			$companies = $supplier->fetchAllBase ( NULL, 'supplier_name ASC' );
			$not_key_companies = $supplier->toArray2 ( $suppliers, null, "\$row->supplier_code - \$row->supplier_name" );
			$key_companies = $supplier->toArray2 ( $suppliers, "\$row->supplier_code - \$row->supplier_name", "\$row->supplier_code - \$row->supplier_name" );
		}
		else //xuat lay khach hang
		{
			$customer = new Admin_Model_Customer ();
			$companies = $customer->fetchAllBase ( NULL, 'customer_name ASC' );
			$not_key_companies = $customer->toArray2 ( $companies, null, "\$row->customer_code - \$row->customer_name" );
			$key_companies = $customer->toArray2 ( $companies, "\$row->customer_code - \$row->customer_name", "\$row->customer_code - \$row->customer_name" );
		}
		$form->inbound_company_code->setJQueryParams ( array ('source' => $not_key_companies ) );
		
		//select lý do nhập kho
		$reason = new Admin_Model_Reason ();
		$reasons = $reason->fetchAllBase ( null );
		$form->inbound_reason_code->setMultiOptions ( array ('' => '- Chọn -' ) + $reason->toArray2 ( $reasons, "reason_code", "reason_content" ) );
		
		//select hàng hóa
		$product = new Admin_Model_Product ();
		$products = $product->fetchAllBase ( null, 'product_code ASC' );
		$form->inbound_detail_product_code->setMultiOptions ( array ('' => '- Chọn -' ) + $product->toArray2 ( $products, "product_code", "product_name" ) );
		$form->inbound_detail_product_code->setLabel ( ucfirst ( $this->string_warehouse_group_name ) );
		
		//select nhóm hàng hóa
		$product_group = new Admin_Model_ProductGroup ();
		$product_groups = $product_group->fetchAllBase ( null, 'product_group_code ASC' );
		$product_groups = array ('' => '- Chọn -' ) + $product_group->toArray2 ( $product_groups, "product_group_code", "product_group_name" );
		$form->product_group_code->setMultiOptions ( $product_groups );
		$form->product_group_code->setLabel ( "Nhóm " . $this->string_warehouse_group_name );
		
		//select thanh phẩm
		$form->inbound_detail_sub_product_code->setMultiOptions ( $product_groups );
		
		//các cột cần lấy dữ liệu
		$select = " 
		SELECT
			`inbound_id`
			, `inbound_code`
			-- , `inbound_type`
			, `inbound_note`
			-- , `inbound_company_code`
			, `inbound_create_time`
			, `inbound_create_user`
			-- , `inbound_warehouse_keep_user`
			-- , `inbound_delivery_user`
			-- , `inbound_order_code`
			, `inbound_warehouse_code`
			, `inbound_status`
			, `inbound_order`
			, `warehouse_name`
			, `account_fullname`
			, (CASE inbound_type WHEN 0 THEN supplier_name ELSE customer_name END) AS company_name 
		FROM tbl_tmp_inbound 
		LEFT JOIN tbl_warehouse ON inbound_warehouse_code = warehouse_code
		LEFT JOIN tbl_customer ON inbound_company_code = customer_code
		LEFT JOIN tbl_supplier ON inbound_company_code = supplier_code
		LEFT JOIN tbl_account ON inbound_create_user = account_username ";
		
		//thiết lập điều kiện lấy dữ liệu
		$where = " WHERE 1 ";
		if ($adminAction != '')
		{
			$form->isValid ( $request->getParams () );
			if ($inbound_code != '')
				$where .= " AND `inbound_code` = '$inbound_code' ";
			else
			{
				if ($inbound_name != '')
					$where .= " AND `inbound_name` LIKE '%$inbound_name%' ";
				if ($inbound_company_code != "")
				{
					$inbound_company_code = explode ( " - ", $inbound_company_code );
					$inbound_company_code = $inbound_company_code [0];
					$where .= " AND `inbound_company_code` = '$inbound_company_code' ";
				}
				if ($account_username != '')
					$where .= " AND `inbound_create_user` = '$account_username' ";
				if ($inbound_create_user != '')
					$where .= " AND `inbound_create_user` = '$inbound_create_user' ";
				if ($inbound_warehouse_code != '')
					$where .= " AND `inbound_warehouse_code` = '$inbound_warehouse_code' ";
				if ($inbound_reason_code != '')
					$where .= " AND `inbound_reason_code` = '$inbound_reason_code' ";
				if ($inbound_create_time_a != "")
				{
					$first_time = $this->_helper->time->first ( $inbound_create_time_a );
					$where .= " AND `inbound_create_time` >= $first_time ";
				}
				if ($inbound_create_time_b != "")
				{
					$last_time = $this->_helper->time->last ( $inbound_create_time_b );
					$where .= " AND `inbound_create_time` <= $last_time ";
				}
				if ($inbound_detail_product_code != "")
					$where .= " AND `inbound_detail_product_code` = '$inbound_detail_product_code' ";
				if ($inbound_detail_sub_product_code != "")
					$where .= " AND `inbound_detail_sub_product_code` = '$inbound_detail_sub_product_code' ";
			}
		}
		
		//thiết lập thứ tự lấy dữ liệu
		$order = $this->_helper->common->getOrderString ( array ('inbound_create_time DESC' ) );
		
		//lấy dữ liệu
		$query = $select . $where . $order;
		$data = $this->_object->queryBase ( $query );
		//phân trang
		$data = $this->_helper->common->paginate ( $data, 10 );
		
		///////////////////////////////////////////////////	
		//Kiem tra xem phai truong hop xuat du lieu excel//
		/////////////////////////////////////////////////// 
		if ($request->isPost () && ($layout != ''))
		{
			$tmp_data = array ('inbound_type' => $this->inbound_type, 'string_inbound_type' => $this->string_inbound_type, 'string_inbound_type_2' => $this->string_inbound_type_2, 'string_warehouse_group_name' => $this->string_warehouse_group_name, 'paginator' => $data );
			return $this->_forward ( 'report', 'index', 'report', array ('type' => "tmp-inbound", 'data' => $tmp_data ) );
		}
		
		//truyền dữ liệu ra view
		$this->view->form = $form;
		$this->view->key_companies = $key_companies;
		$this->view->report_type = $report_type;
		$this->view->account_username = $account_username;
	}

	//kích hoạt/ vô hiệu hóa 1 hoặc nhiều dòng
	public function publishAction()
	{
		$this->_helper->action->publish ( $this->_object, 'inbound_status' );
	}

	//thêm phiếu xuất kho.
	public function insertAction()
	{
		//lấy tham số
		$request = $this->_request;
		
		//Them loai phieu nhap...
		$this->_setInboundString ( $request->getParam ( 'inbound_warehouse_group_code' ), 1 );
		
		//tạo form
		$form = new Inbound_Form_Inbound_Insert ( $this );
		
		//select lý do nhập kho
		$reason = new Admin_Model_Reason ();
		$sql = "
		SELECT * 
		FROM view_reason 
		WHERE 
			reason_inbound_type = '{$this->inbound_type}' 
			AND reason_warehouse_group_code = '{$this->inbound_warehouse_group_code}'
		";
		$reasons = $reason->queryBase ( $sql );
		$not_reasons = $reason->toArray2 ( $reasons, null, "\$row->reason_code - \$row->reason_content" );
		$form->inbound_reason_code->setJQueryParams ( array ('source' => $not_reasons ) );
		$not_reasons_2 = $reason->toArray2 ( $reasons, "\$row->reason_code - \$row->reason_content", "reason_use_company" );
		$form->inbound_reason_code_2->setMultiOptions ( array ('' => '- Chọn -' ) + $not_reasons_2 );
		
		//select kho nhập hàng
		$warehouse = new Admin_Model_Warehouse ();
		$sql = "
		SELECT * 
		FROM view_warehouse
		ORDER BY warehouse_name ASC";
		$warehouses = $warehouse->queryBase ( $sql );
		$warehouses = $warehouse->toArray2 ( $warehouses, 'warehouse_code', 'warehouse_name' );
		$form->inbound_warehouse_code->setMultiOptions ( array ('' => '- Chọn -' ) + $warehouses );
		
		//Lay thong tin thủ kho
		$account = new Admin_Model_Account ();
		$sql = "
		SELECT * 
		FROM view_account
		ORDER BY account_fullname ASC";
		$accounts = $account->queryBase ( $sql );
		$accounts = $account->toArray2 ( $accounts, 'account_username', 'account_fullname' );
		$form->inbound_warehouse_keep_user->setMultiOptions ( array ('' => '- Chọn -' ) + $accounts );
		
		//Lay thong tin ncc, khach hàng
		if ($this->inbound_type == '0')
		{
			$supplier = new Admin_Model_Supplier ();
			$suppliers = $supplier->fetchAllBase ();
			$not_key_companies = $supplier->toArray2 ( $suppliers, null, "\$row->supplier_code - \$row->supplier_name" );
		}
		else
		{
			$customer = new Admin_Model_Customer ();
			$customers = $customer->fetchAllBase ();
			$not_key_companies = $customer->toArray2 ( $customers, null, "\$row->customer_code - \$row->customer_name" );
		}
		$form->inbound_company_code->setJQueryParams ( array ('source' => $not_key_companies ) );
		
		//lay ma phieu
		$max_inbound_code = $this->_object->fetchInboundCode ( $this->inbound_warehouse_group_code );
		$form->inbound_code->setValue ( $max_inbound_code );
		
		//loai phieu
		$warehouse_group = new Admin_Model_WarehouseGroup ();
		$warehouse_group_name = $warehouse_group->fetchOneBase ( "warehouse_group_name", "warehouse_group_code='$this->inbound_warehouse_group_code'" );
		$form->inbound_type->setValue ( $this->string_inbound_type . " kho " . $warehouse_group_name );
		
		//ngày tao phieu
		$form->inbound_create_time->setValue ( $this->_helper->format->time (time()) );
		
		//nguoi tao phieu
		$form->inbound_create_user->setValue ( Zend_Registry::get ( "auth" )->account_fullname );
		
		//Lay don vi tinh
		$unit = new Admin_Model_Unit ();
		$sql = "
		SELECT * 
		FROM view_unit 
		ORDER BY unit_name ASC";
		$units = $unit->queryBase ( $sql );
		
		//Lay thong tin ma hang hoa ho tro autocomplete
		$select = " 
		SELECT
			product_id AS `inventory_id`
			,`inventory_product_code`
			, `inventory_product_unit_code`
			, '' AS inventory_quantity
			, '' AS `inventory_lot_code`
			, '' AS `inventory_product_time`
			, '' AS `inventory_expire_time`
			, '' AS `inventory_location_code`
			, '' AS `location_name`
			, `product_name`
		FROM 
			tbl_product LEFT JOIN tbl_inventory ON product_code = inventory_product_code
		WHERE product_warehouse_group_code='{$this->inbound_warehouse_group_code}'
		GROUP BY inventory_product_code 
		";
		$inventory = new Admin_Model_Inventory ();
		$inventorys = $inventory->queryBase ( $select );
		foreach ( $inventorys as $key => $inventory )
		{
			$array_inventorys [$key] = $inventory->toArray ();
			//$array_inventorys [$key] ['inventory_product_time'] = date ( 'd.m.Y', $inventory->inventory_product_time );
			//$array_inventorys [$key] ['inventory_expire_time'] = date ( 'd.m.Y', $inventory->inventory_expire_time );
			$array_inventorys [$key] ['product_name'] = $inventory->m_Array ['product_name'];
		
		//$array_inventorys [$key] ['location_name'] = $inventory->m_Array ['location_name'];
		}
		
		//Lay thong tin ma hang hoa thanh pham.
		//$product = new Admin_Model_Product ();
		//$products = $product->getDbTable ()->getAdapter ()->fetchCol ( "SELECT product_code FROM view_product WHERE product_warehouse_group_code = 'TP'" );
		

		//phần xử lí chính khi post giá trị
		if ($request->isPost ()) //khi post giá trị
		{
			$postValues = $request->getPost ();
			$form->inbound_company_code->setRequired ( false );
			if ($form->isValid ( $postValues )) //khi giá trị trong form đã được kiểm tra thành công
			{
				$adminAction = $form->getValue ( 'adminAction' );
				
				//kiểm tra có trùng code không, nếu trùng báo lỗi
				if ($this->_object->isExist ( 'inbound_code', $form->inbound_code->getValue () ))
					$form->inbound_code->setValue ( $this->_object->fetchInboundCode ( $this->inbound_warehouse_group_code ) );
				
		//phieu chinh
				$inbound = new Admin_Model_TmpInbound ( $form->getValues () );
				$inbound->inbound_type = $this->inbound_type; //Loai phieu...
				$inbound->inbound_warehouse_group_code = $this->inbound_warehouse_group_code; //
				$inbound->inbound_create_user = Zend_Registry::get ( 'auth' )->account_username;
				$inbound->inbound_create_time=time();
				
				//li do nhap xuat kho
				$inbound_reason_code = $inbound->inbound_reason_code;
				$inbound_reason_code = explode ( " - ", $inbound_reason_code );
				$inbound->inbound_reason_code = $inbound_reason_code [0];
				if ($not_reasons_2 [$form->getValue ( 'inbound_reason_code_2' )] != 1)
					$inbound->inbound_company_code = '';
				
		//Lay thong tin inbound_detail dang mang POST sang mang cac doi tuong Model...
				$inbound_details = array ();
				foreach ( ( array ) $postValues ['inbound_detail_product_code'] as $key => $value )
				{
					$inbound_detail = new Admin_Model_TmpInboundDetail ();
					$inbound_detail->inbound_detail_inbound_code = $inbound->inbound_code;
					$inbound_detail->inbound_detail_product_code = $postValues ['inbound_detail_product_code'] [$key];
					$inbound_detail->inbound_detail_product_unit_code = $postValues ['inbound_detail_product_unit_code'] [$key];
					$inbound_detail->inbound_detail_product_quantity = $postValues ['inbound_detail_product_quantity'] [$key];
					$inbound_detail->inbound_detail_location_code = $postValues ['inbound_detail_location_code'] [$key];
					$inbound_detail->inbound_detail_product_time = $postValues ['inbound_detail_product_time'] [$key];
					$inbound_detail->inbound_detail_expire_time = $postValues ['inbound_detail_expire_time'] [$key];
					$inbound_detail->inbound_detail_lot_code = $postValues ['inbound_detail_lot_code'] [$key];
					$inbound_detail->inbound_detail_note = $postValues ['inbound_detail_note'] [$key];
					$inbound_detail->inbound_detail_sub_product_code = $postValues ['inbound_detail_sub_product_code'] [$key];
					$inbound_details [] = $inbound_detail;
				}
				
				//xu lí khi không có lỗi				
				if (! $form->isErrors ())
				{
					try
					{
						//insert phieu
						$inbound->insertBase ();
						
						//Thuc hien them chi tiet phieu...
						foreach ( $inbound_details as $inbound_detail )
						{
							/*if (( string ) $inbound_detail->inbound_detail_sub_product_code != '')
							{
								$tmp = explode ( " - ", $inbound_detail->inbound_detail_sub_product_code );
								$inbound_detail->inbound_detail_sub_product_code = $tmp [0];
							}*/
							
							$inbound_detail->insertBase ();
						}
						
						//thông báo + chuyển hướng trang khi thành công				
						$this->_helper->flashMessenger ( "Thêm thành công phiếu mới với mã phiếu: <span class='red'>{$inbound->inbound_code}</span>" );
						if ($adminAction == 'save-and-close')
						{
							$this->_helper->redirector ( 'index', 'index', 'tmp-inbound', array () );
						}
						else if ($adminAction == 'apply')
						{
							$this->_helper->redirector ( 'detail', 'index', 'tmp-inbound', array ('id' => $inbound->inbound_id ) );
						}
						else if ($adminAction == 'save-and-new')
						{
							$this->_helper->redirector ( 'insert-out', 'index', 'tmp-inbound', array ('inbound_warehouse_group_code' => $this->inbound_warehouse_group_code ) );
						}
					}
					catch ( Exception $e )
					{
						echo $e->getMessage ();
					}
				}
			}
		}
		else //khi vào form lần đầu tiên
		{
			//kiểm tra phải copy không, nếu phải thì đổ dữ liệu vào
			$form->inbound_warehouse_code->setValue ( $request->getParam ( 'inbound_warehouse_code' ) );
			$form->inbound_warehouse_keep_user->setValue ( $request->getParam ( 'inbound_warehouse_keep_user' ) );
			$form->inbound_reason_code->setValue ( $request->getParam ( 'inbound_reason_code' ) );
			$form->inbound_note->setValue ( $request->getParam ( 'inbound_note' ) );
			$form->inbound_company_code->setValue ( $request->getParam ( 'inbound_company_code' ) );
			$form->inbound_delivery_user->setValue ( $request->getParam ( 'inbound_delivery_user' ) );
		}
		
		//Load CSS/JS files...
		$this->view->headScript ()->appendFile ( JS . 'jquery/js/jquery-ui.custom.min.js' );
		$this->view->headLink ()->appendStylesheet ( JS . 'jquery/css/smoothness/jquery-ui.custom.css' );
		$this->view->headLink ()->appendStylesheet ( CSS . 'admin/inbound.css' );
		
		//truyền dữ liệu ra view
		$this->view->inbound_warehouse_group_code = $this->inbound_warehouse_group_code;
		$this->view->form = $form;
		$this->view->units = $units;
		$this->view->array_inventorys = $array_inventorys;
		$this->view->inbound_details = $inbound_details;
		$this->view->products = $products;
	}

	//xem chi tiet 1 dòng
	public function detailAction()
	{
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		
		//forward
		$this->_forward ( 'detail', 'index', 'inbound', array ('id' => $id, 'tmp' => '1' ) );
	}

	//cap nhat 1 dòng
	public function updateAction()
	{
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		
		//forward
		$this->_forward ( 'update', 'index', 'inbound', array ('id' => $id, 'tmp' => '1' ) );
	}

	//print phiếu nhập xuất kho
	public function printAction()
	{
		//Dung layout ajax
		$this->getHelper ( 'Layout' )->setLayout ( 'print' );
		
		//lấy tham số
		$request = $this->_request;
		$id = $request->getParam ( 'id' );
		
		//forward
		$this->_forward ( 'print', 'index', 'inbound', array ('id' => $id, 'tmp' => '1' ) );
	}
}